#!/usr/bin/env python
# encoding: utf-8

"""I18n implementation for spyro.
"""

import gettext
import logging
import sys

log = logging.getLogger(__name__)

class Translator:
    """Provides an integrated solution built over the standard gettext
    implementation to translate and internationalize your application.
    """
    
    def __init__(self):
        from spyro.config.register import Register
        self.config = Register.i18n
        self.langs = list()

    def set_lang(self, identifier):
        """Sets the current language to `identifier`.
        """

        if identifier in self.config['installed_langs']:
            self.langs.append(identifier)

    def get_user_lang(self):
        """Searches for the client preferences by parsing the
        HTTP_ACCEPT_LANGUAGE header value and sets the appropriate
        language if it matches one of the `installed_langs`.
        If there is no matching language or there is not HTTP_ACCEPT_LANGUAGE

        """
        
        request = sys._getframe(1).f_locals['self'].request
        http_accept_language = request.server('HTTP_ACCEPT_LANGUAGE',
                                              None)

        log.debug('HTTP_ACCEPT_LANGUAGE found: %s' % (http_accept_language))

        if http_accept_language is not None:
            for language in http_accept_language.split(','):
                lang = language.split(';')[0]
                lang = lang.split('-')[0]

                # validation
                if lang in self.config['installed_langs']:
                    if not lang in self.langs:  # avoid duplicates
                        self.langs.append(lang.strip())
        # if there is no accepted lang or there is no header value
        # the default value will be added by the translate method.
        # so we don't do it here.

        log.debug('Accepted languages: %s' % str(self.langs))

    def translate(self):
        """Returns a standard Translations object usable, for example, as
        parameter for the Request.from_template method.
        You can do it by passing this return value as a keyword parameter
        named `translation` to the from_template method.
        If was not setted any language will be used the "default" one
        found in the configuration.
        """

        if len(self.langs) < 1:
            self.langs.append(self.config['default'])

        return gettext.translation(self.config['domain'],
                                    self.config['localedir'],
                                    languages=self.langs,
                                    fallback=self.config['fallback'])
